package com.hoas.api.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
	
	public static String execute(HttpRequestBase method, String charset) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse resp = client.execute(method);
		// The underlying HTTP connection is still held by the response object
		// to allow the response content to be streamed directly from the network socket.
		// In order to ensure correct deallocation of system resources
		// the user MUST call CloseableHttpResponse#close() from a finally clause.
		// Please note that if response content is not fully consumed the underlying
		// connection cannot be safely re-used and will be shut down and discarded
		// by the connection manager. 
		try {
		    return EntityUtils.toString(resp.getEntity(), charset);
		    // do something useful with the response body
		    // and ensure it is fully consumed
		} finally {
			resp.close();
		}

	}
	
	public static String get(String url, Map<String,String> headers, String charset) throws IOException {
		HttpGet getMethod = new HttpGet(url);
		if(headers != null) {
			for(String key : headers.keySet()) {
				getMethod.addHeader(key, headers.get(key));
			}
		}
		return execute(getMethod, charset);
	}
	
	public static String post(String url, Map<String,String> headers, Map<String,?> params, String charset) throws IOException {
		HttpPost postMethod = new HttpPost(url);
		if(headers != null) {
			for(String key : headers.keySet()) {
				postMethod.addHeader(key, headers.get(key));
			}
		}
		
		if(headers != null) {
			List <NameValuePair> paramsData = new ArrayList<NameValuePair>();
			for(String key : params.keySet()) {
				paramsData.add(new BasicNameValuePair(key, (String) params.get(key)));
			}
			postMethod.setEntity(new UrlEncodedFormEntity(paramsData));
		}
		
		return execute(postMethod, charset);
		
	}
	
}
